package com.junyi.annotation;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.core.annotation.AnnotatedElementUtils;

import java.lang.annotation.Inherited;

/**
 * @time: 2022/6/15 14:28
 * @version: 1.0
 * @author: junyi Xu
 * @description:
 */
@Slf4j
public class Main {


    @Test
    public void test() throws NoSuchMethodException {
        A a = new A();
        log.info("A class: {}", getValue(a.getClass().getAnnotation(Paper.class)));
        log.info("A method: {}", getValue(a.getClass().getMethod("process").getAnnotation(Paper.class)));

        // 注解@Paper如果没有加 @Inherited，那么下面的内容都是空的
        // 如果加了@Inherited，那么类上面的注解值可以获取到，方法上面的注解值是空
        B b = new B();
        log.info("B class: {}", getValue(b.getClass().getAnnotation(Paper.class)));
        log.info("B method: {}", getValue(b.getClass().getMethod("process").getAnnotation(Paper.class)));
    }

    /** 工具类 AnnotatedElementUtils，帮助我们找出父类和接口、父类方法和接口方法上的注解
     *  可以处理子类方法注解值的问题，注解@Paper不需要加 @Inherited */
    @Test
    public void test2() throws NoSuchMethodException {
        B b = new B();
        log.info("B class: {}", getValue(AnnotatedElementUtils.findMergedAnnotation(b.getClass(), Paper.class)));
        log.info("B method: {}", getValue(AnnotatedElementUtils.findMergedAnnotation(b.getClass().getMethod("process"), Paper.class)));
    }


    public String getValue(Paper annotation) {
        if (annotation == null) {
            return "";
        }
        return annotation.value();
    }
}
